package com.zkthink.ceres.order.controller;

import cn.hutool.extra.servlet.ServletUtil;
import com.zkthink.ceres.common.annotations.IgnoreTenant;
import com.zkthink.ceres.member.dto.MemberDTO;
import com.zkthink.ceres.member.entity.Member;
import com.zkthink.ceres.member.service.MemberService;
import com.zkthink.ceres.order.dto.*;
import com.zkthink.ceres.order.entity.Order;
import com.zkthink.ceres.order.enums.ReturnGoodsReasonEnum;
import com.zkthink.ceres.order.enums.ReturnMoneyReasonEnum;
import com.zkthink.ceres.order.service.OrderService;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.zkthink.base.controller.SuperController;
import com.zkthink.base.R;
import com.zkthink.ceres.order.service.ReturnInterventionAdminService;
import com.zkthink.ceres.order.service.ReturnInterventionService;
import com.zkthink.ceres.product.dto.IdQueryDTO;
import com.zkthink.ceres.product.dto.StoreDTO;
import com.zkthink.ceres.store.dto.StoreInfoDTO;
import com.zkthink.ceres.store.entity.Store;
import com.zkthink.ceres.store.service.StoreService;
import com.zkthink.ceres.tenant.entity.Tenant;
import com.zkthink.ceres.tenant.service.TenantService;
import com.zkthink.context.BaseContextHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.zkthink.security.annotation.PreAuth;

import javax.servlet.http.HttpServletRequest;


/**
 * <p>
 * 前端控制器
 * 
 * </p>
 *
 * @author JustArgo
 * @date 2020-05-10
 */
@Slf4j
@Validated
@RestController
@AllArgsConstructor
@RequestMapping("/order")
@Api(value = "订单接口", tags = "订单接口")
@PreAuth(replace = "order:")
public class OrderController /*extends SuperController<OrderService, Long, Order, OrderPageDTO, OrderSaveDTO, OrderUpdateDTO> */{

    private OrderService baseService;

    private ReturnInterventionAdminService returnInterventionAdminService;

    private StoreService storeService;

    private MemberService memberService;

    private TenantService tenantService;

    /**
     * Excel导入后的操作
     *
     * @param
     */
    /*@Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<Order> orderList = list.stream().map((map) -> {
            Order order = Order.builder().build();
            //TODO 请在这里完成转换
            return order;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(orderList));
    }*/

    @ApiOperation("审核退款")
    @PostMapping("/auditReturnMoney")
    public R<Boolean> auditReturnMoney(@RequestBody AuditReturnMoneyDTO auditReturnMoneyDTO){
        return baseService.auditReturnMoney(auditReturnMoneyDTO);
    }

    @ApiOperation("审核退货")
    @PostMapping("/auditReturnGoods")
    public R<Boolean> auditReturnGoods(@RequestBody AuditReturnGoodsDTO auditReturnGoodsDTO){
        return baseService.auditReturnGoods(auditReturnGoodsDTO);
    }

    @ApiOperation("发货")
    @PostMapping("/sendGoods")
    public R<Boolean> sendGoods(@RequestBody SendGoodsDTO sendGoodsDTO){
        return baseService.sendGoods(sendGoodsDTO);
    }

    @ApiOperation("确认收到退货")
    @PostMapping("/confirmReturnGoods")
    public R<Boolean> confirmReturnGoods(@RequestBody ConfirmReturnGoodsDTO confirmReturnGoodsDTO){
        return baseService.confirmReturnGoods(confirmReturnGoodsDTO);
    }

    @ApiOperation("搜索订单")
    @PostMapping("/findAdminOrderList")
    public R<AdminOrderListDTO> findAdminOrderList(@RequestBody AdminOrderSearchParamDTO adminOrderSearchParamDTO){
        if(adminOrderSearchParamDTO.getSource() != null && adminOrderSearchParamDTO.getSource() == 1){
            BaseContextHandler.setTenant(null);
        }
        return baseService.findAdminOrderList(adminOrderSearchParamDTO);
    }

    @ApiOperation("搜索售后订单")
    @PostMapping("/findAdminReturnOrderList")
    public R<AdminOrderListDTO> findAdminReturnOrderList(@RequestBody AdminOrderSearchParamDTO adminOrderSearchParamDTO){
        return baseService.findAdminReturnOrderList(adminOrderSearchParamDTO);
    }

    @ApiOperation("查看订单详情")
    @PostMapping("/getAdminOrderDetail")
    public R<AdminOrderDetailDTO> findAdminOrderDetail(@RequestBody IdQueryDTO idQueryDTO){
        return baseService.findAdminOrderDetail(idQueryDTO);
    }

    @ApiOperation("查询售后理由")
    @GetMapping("/getReasonEnums")
    public R<Map<String,Object>> getReasonEnums(){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("returnMoneyReasonList", ReturnMoneyReasonEnum.generateList());
        map.put("returnGoodsReasonList", ReturnGoodsReasonEnum.generateList());
        return R.success(map);
    }

    @ApiOperation("生成支付二维码")
    @PostMapping("/generatePayQrCode")
    public R<String> generatePayQrCode(HttpServletRequest request, @RequestBody PayQrCodeDTO payQrCodeDTO){
        String ip = ServletUtil.getClientIP(request);
        payQrCodeDTO.setIp(ip);
        return baseService.generatePayQrCode(payQrCodeDTO);
    }

    @ApiOperation("查询二维码支付结果")
    @GetMapping("/queryPayQrCodeResult/{orderId}")
    public R<String> queryPayQrCodeResult(@PathVariable("orderId") String orderId){
        return baseService.queryPayQrCodeResult(orderId);
    }

    @ApiOperation("查询平台介入列表")
    @PostMapping("/findReturnInterventionList")
    public R<ReturnInterventionPageDTO> findReturnInterventionList(@RequestBody QueryReturnInterventionDTO queryDTO){
        BaseContextHandler.setTenant("");
        return returnInterventionAdminService.findReturnInterventionList(queryDTO);
    }

    @ApiOperation("审核平台介入")
    @PostMapping("/auditReturnIntervention")
    public R<Boolean> auditReturnIntervention(@RequestBody AuditReturnInterventionDTO returnInterventionDTO){
        BaseContextHandler.setTenant("");
        return returnInterventionAdminService.auditReturnIntervention(returnInterventionDTO);
    }

    @ApiOperation("查询平台介入详情")
    @GetMapping("/getReturnInterventionDetail/{id}")
    public R<ReturnInterventionDetailDTO> getReturnInterventionDetail(@PathVariable("id") Long id){
        BaseContextHandler.setTenant("");
        return returnInterventionAdminService.getReturnInterventionDetail(id);
    }

    @ApiOperation("查询买家信息")
    @GetMapping("/getMemberInfo/{mid}")
    public R<MemberDTO> getMemberInfo(@PathVariable("mid") Long mid){
        BaseContextHandler.setTenant("");
        Member member = memberService.getById(mid);
        if(member==null){
            return R.fail("用户不存在");
        }
        MemberDTO memberDTO = new MemberDTO();
        memberDTO.setMemberAccount(member.getNickname()+"_"+member.getOpenid());
        memberDTO.setCreateTime(member.getCreateTime());
        MemberOrderStatistics orderStatistics = baseService.getOrderStatisticsByMid(mid);
        memberDTO.setOrderCount(orderStatistics.getOrderCount());
        memberDTO.setPhone(member.getPhone());
        memberDTO.setReturnCount(orderStatistics.getReturnCount());
        memberDTO.setReturnSucPercent(orderStatistics.getReturnSucPercent());
        return R.success(memberDTO);
    }

    @ApiOperation("平台介入查询店铺信息")
    @GetMapping("/getStoreInfo/{storeId}")
    public R<StoreInfoDTO> getStoreInfo(@PathVariable("storeId") Long storeId){
        BaseContextHandler.setTenant("");
        Store store = storeService.getById(storeId);
        if(store==null){
            return R.fail("店铺不存在");
        }
        StoreInfoDTO storeInfoDTO = new StoreInfoDTO();
        storeInfoDTO.setId(storeId);
        storeInfoDTO.setStoreName(store.getStoreName());
        storeInfoDTO.setAddress(StringUtils.trimToEmpty(store.getRefundAddress()));
        storeInfoDTO.setContactName(StringUtils.trimToEmpty(store.getRefundContact()));
        storeInfoDTO.setContactPhone(store.getMobile());
        Tenant tenant = tenantService.getByCode(storeService.findTenantCodeByStoreId(storeId));
        LocalDateTime startTime = tenant.getStartTime();
        LocalDateTime endTime = startTime.plusYears(tenant.getExpireLimitYear());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        storeInfoDTO.setContractTime(formatter.format(startTime) + " -- " + formatter.format(endTime));
        return R.success(storeInfoDTO);
    }

    @ApiOperation("查询物流轨迹")
    @GetMapping("/getShippingTrace/{shipperCode}/{logisticCode}")
    public R<ShippingDTO> getShippingTrace(@PathVariable("shipperCode") String shipperCode, @PathVariable("logisticCode") String logisticCode){
        return R.success(baseService.getShippingTrace(shipperCode, logisticCode));
    }

    @ApiOperation("查询数据")
    @IgnoreTenant
    @GetMapping("/getOrderStatisticsByMid/{mid}")
    public R<MemberOrderStatistics> getOrderStatisticsByMid(@PathVariable("mid") Long mid){
        return R.success(baseService.getOrderStatisticsByMid(mid));
    }
}
